package com.project.poetry.common.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.project.poetry.common.util.CommonUtil;
import com.project.poetry.service.entity.po.user.UserPO;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @author mengxj
 */
@Slf4j
@Component
public class PoetryObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        String currentUserName = this.getUsername();
        LocalDateTime nowDateString = CommonUtil.nowDateTime();
        this.setProperties(metaObject, "createTime", nowDateString);
        this.setProperties(metaObject, "createBy", currentUserName);
        this.setProperties(metaObject, "updateTime", nowDateString);
        this.setProperties(metaObject, "updateBy", currentUserName);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        String currentUserName = this.getUsername();
        this.setProperties(metaObject, "updateTime", CommonUtil.nowDateTime());
        this.setProperties(metaObject, "updateBy", currentUserName);
    }

    private String getUsername(){
        String currentUserName = null;
        try {
            UserPO user = CommonUtil.getUser();
            currentUserName = Objects.isNull(user) ? null : user.getUsername();
        }catch (Exception e){
            log.error("未获取到登陆人或者是调度任务");
        }
        return currentUserName;
    }

    private void setProperties(MetaObject metaObject, String column, Object value){
        if(metaObject.hasSetter(column)){
            this.setFieldValByName(column, value, metaObject);
        }
    }
}
